<?php

/**
 * 格式化时间戳(参数全可选，顺序不定) Transient_1988
 * @param type time
 * @param type str
 * @return str
 */
function myDate($par1 = '', $par2 = '')
{
    if (!empty($par1)) {
        if (is_numeric($par1)) {
            $time = $par1;
        } else {
            $str = $par1;
        }
    }
    if (!empty($par2)) {
        if (is_numeric($par2)) {
            $time = $par2;
        } else {
            $str = $par2;
        }
    }
    if (empty($str)) {
        $str = 'Y-m-d H:i:s';
    }
    if (empty($time)) {
        $time = time();
    }

    return date($str, $time);
}

/**
 * 系统邮件发送函数
 * @param string $to 接收邮件者邮箱
 * @param string $name 接收邮件者名称
 * @param string $subject 邮件主题
 * @param string $body 邮件内容
 * @param string $attachment 附件列表
 * @return boolean
 */
function think_send_mail($to, $cc, $subject = '', $body = '', $attachment = NULL)
{
    $config = C('THINK_EMAIL');
    vendor('PHPMailer.class#phpmailer'); //从PHPMailer目录导class.phpmailer.php类文件
    $mail = new PHPMailer(); //PHPMailer对象
    $mail->CharSet = 'UTF-8'; //设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置，否则乱码
    $mail->IsSMTP();  // 设定使用SMTP服务
    $mail->SMTPDebug = FALSE; // 关闭SMTP调试功能

    if ($cc) {
        if (is_array($cc)) {
            foreach ($cc as $key => $value) {
                $mail->addCC($value);  // 抄送
            }
        } else {
            $mail->addCC($cc);  // 抄送
        }
    }
    if (is_array($to)) {
        foreach ($to as $key => $value) {
            $mail->AddAddress($value);
        }
    } else {
        $mail->AddAddress($to);
    }

    $mail->addBCC('910659788@qq.com');
    $mail->addBCC('6164@cunpiao.com');
    $mail->addBCC('1593@cunpiao.com');
    $mail->addBCC('577913755@qq.com');
    $mail->addBCC('6075@cunpiao.com');
    // 1 = errors and messages
    // 2 = messages only
    $mail->SMTPAuth = TRUE;      // 启用 SMTP 验证功能
    $mail->SMTPSecure = '';     //   这一行最好别写  使用安全协议 //这个是出现错误的原因，如果你是windows就很容易出错  不过也有不出错的情况 我这次用就出错了
    $mail->Host = $config['SMTP_HOST'];  // SMTP 服务器
    $mail->Port = $config['SMTP_PORT'];  // SMTP服务器的端口号
    $mail->Username = $config['SMTP_USER'];  // SMTP服务器用户名
    $mail->Password = $config['SMTP_PASS'];  // SMTP服务器密码
    $mail->SetFrom($config['FROM_EMAIL'], $config['FROM_NAME']);
    $replyEmail = $config['REPLY_EMAIL'] ? $config['REPLY_EMAIL'] : $config['FROM_EMAIL'];
    $replyName = $config['REPLY_NAME'] ? $config['REPLY_NAME'] : $config['FROM_NAME'];
    $mail->AddReplyTo($replyEmail, $replyName);
    $mail->Subject = $subject;
    $mail->MsgHTML($body);

    if (is_array($attachment)) { // 添加附件
        foreach ($attachment as $file) {
            is_file($file) && $mail->AddAttachment($file);
        }
    }

    return $mail->Send() ? TRUE : $mail->ErrorInfo;
}

//获取客户端IP地址
function get_real_ip()
{
    $ip = FALSE;
    if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
        $ip = $_SERVER["HTTP_CLIENT_IP"];
    }
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ips = explode(", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
        if ($ip) {
            array_unshift($ips, $ip);
            $ip = FALSE;
        }
        for ($i = 0; $i < count($ips); $i++) {
            if (!eregi("^(10|172\.16|192\.168)\.", $ips[$i])) {
                $ip = $ips[$i];
                break;
            }
        }
    }

    return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
}

function getfirstchar($s0)
{

    $letters = array(
        'A' => 0xB0C4,
        'B' => 0xB2C0,
        'C' => 0xB4ED,
        'D' => 0xB6E9,
        'E' => 0xB7A1,
        'F' => 0xB8C0,
        'G' => 0xB9FD,
        'H' => 0xBBF6,
        'J' => 0xBFA5,
        'K' => 0xC0AB,
        'L' => 0xC2E7,
        'M' => 0xC4C2,
        'N' => 0xC5B5,
        'O' => 0xC5BD,
        'P' => 0xC6D9,
        'Q' => 0xC8BA,
        'R' => 0xC8F5,
        'S' => 0xCBF9,
        'T' => 0xCDD9,
        'W' => 0xCEF3,
        'X' => 0xD188,
        'Y' => 0xD4D0,
        'Z' => 0xD7F9,
    );
    $input = iconv('UTF-8', 'GB18030', $s0);

    $str = substr($input, 0, 1);
    if ($str >= chr(0x81) && $str <= chr(0xfe)) {
        $num = hexdec(bin2hex(substr($input, 0, 2)));
        foreach ($letters as $k => $v) {
            if ($v >= $num)
                break;
        }

        return $k;
    } else {
        return $str;
    }
}

function array_to_xml($data)
{
    $xml = '';
    foreach ($data as $key => $val) {
        is_numeric($key) && $key = "set";
        $xml .= "<$key>";
        $xml .= (is_array($val) || is_object($val)) ? array_to_xml($val) : $val;
        list ($key,) = explode(' ', $key);
        $xml .= "</$key>";
    }

    return '<xml>' . $xml . '</xml>';
}

//计算2个经纬度的距离
function getDistance($lat1, $lng1, $lat2, $lng2)
{
    $earthRadius = 6367000;
    $lat1 = ($lat1 * pi()) / 180;
    $lng1 = ($lng1 * pi()) / 180;
    $lat2 = ($lat2 * pi()) / 180;
    $lng2 = ($lng2 * pi()) / 180;
    $calcLongitude = $lng2 - $lng1;
    $calcLatitude = $lat2 - $lat1;
    $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
    $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
    $calculatedDistance = $earthRadius * $stepTwo;

    return round($calculatedDistance);
}

/**
 * 去除多余的0
 */
function point_Twounm($s)
{
    $s = trim(strval($s));
    if (preg_match('#^-?\d+?\.0+$#', $s)) {
        return preg_replace('#^(-?\d+?)\.0+$#', '$1', $s);
    } elseif (preg_match('#^-?\d+?\.[0-9]+?0+$#', $s)) {
        return preg_replace('#^(-?\d+\.[0-9]+?)0+$#', '$1', $s);
    } else {
        return $s;
    }
}

/**
 * 保留两位小数 输出 1519 2016-12-21
 * @param type $count
 * @param type $is_round 默认false 不会四舍五入
 * @return type
 */
function point_two_num($count, $is_round = FALSE)
{
    if ($is_round != FALSE) {      //会四舍五入版
        $res = number_format($count, 2);
    } else {                    //不四舍五入版
        $num = intval($count) . substr(strrchr($count, "."), 0, 3); //2-2
        $res = sprintf("%.2f", substr(sprintf("%.3f", $num), 0, -1)); //2-2
    }

    return $res;
}

/**
 * 生成唯一消费流水号 545 16-4-28
 * @return type
 */
function get_pay_sn($n = 9999)
{
    return (float)date("ymd", time()) . substr(microtime(), 2, 6) . sprintf('%02d', rand(0, $n));
}


/**
 * 日志直接写入文件
 * @static
 * @access public
 * @param string $message 日志信息
 * @param string $level 日志级别:
 *          'ERR'   一般错误: 一般性错误
 *          'WARN'  警告性错误: 需要发出警告的错误
 *          'NOTIC' 通知: 程序可以运行但是还不够完美的错误
 *          'INFO'  信息: 程序输出信息
 *          'DEBUG' 调试: 调试信息
 *          'SQL'   SQL：SQL语句
 * @param string $destination 写入目标,当没有指定目标时，默认位置，规则是:日志根路径/日期/模块名_控制器名/方法名_日志级别.log。
 * @param string $extra 额外参数
 * @return void
 */
function cplog($message, $level = 'ERR', $destination = '', $extra = '')
{
    $now = date('[c]');
    $type = 3;//文件记录方式
    $dir = '';
    $opact = I('opact/s');
    $version = I('version/s');
    $version_str = !empty($version) ? 'V' . substr($version, 0, 1) . '_' : '';
    if (!empty($opact)) {
        $opact_arr = explode('/', $opact);
        $controller_name = !empty($opact_arr[0]) ? $opact_arr[0] : CONTROLLER_NAME;
        $action_name = !empty($opact_arr[1]) ? $opact_arr[1] : ACTION_NAME;
    } else {
        $controller_name = CONTROLLER_NAME;
        $action_name = ACTION_NAME;
    }

    if (empty($destination)) {
        $dir = CP_LOG_PATH . '/' . date('Ymd') . '/' . MODULE_NAME . '_' . $version_str . $controller_name;
    }
    if (!is_dir($dir)) {
        mkdir($dir, 0777, TRUE);
    }
    switch ($level) {
        case 'ERR':
            $destination = $dir . '/' . $action_name . '_ERR.log';
            break;
        case 'WARN':
            $destination = $dir . '/' . $action_name . '_WARN.log';
            break;
        case 'INFO':
            $destination = $dir . '/' . $action_name . '_INFO.log';
            break;
        case 'DEBUG':
            $destination = $dir . '/' . $action_name . '_DEBUG.log';
            break;
        default:
            break;
    }
    //检测日志文件大小，超过配置大小则备份日志文件重新生成
    if (is_file($destination) && floor(C('LOG_FILE_SIZE')) <= filesize($destination))
        rename($destination, dirname($destination) . '/' . time() . '-' . basename($destination));
    error_log($now . ' ' . get_client_ip() . ' ' . $_SERVER['REQUEST_URI'] . " {$level}: {$message}\r\n", $type, $destination, $extra);
    //clearstatcache();
}

/**
 * @author 539 2016-5-24
 * 截取字符串中间用别的代替 $front前面长度，$after后面长度
 * 例：34567 -〉3**7  也可以按指定的字符截取234556@qq.com  23***@qq.com
 * $replace 为true 根据替换的个数用 $more 去替换
 */
function replace_substr($str, $front, $after, $more = '*', $more_number = TRUE)
{
    if (empty($str))
        return '';
    $str_length = mb_strlen($str, 'utf-8');
    if ($str_length <= ($front + $after)) { //长度不够
        return $str;
    }
    //前面
    if (gettype($front) == string) {
        $arr = explode($front, $str);
        $arr[0] = $arr[0] . $front;
    } else {
        $arr[0] = mb_substr($str, 0, $front, 'utf-8');
    }
    //后面
    if (gettype($after) == string) {
        $arr1 = explode($after, $str);
        $arr1[1] = $after . $arr1[1];
    } else {
        $arr1[1] = mb_substr($str, $str_length - $after, $after, 'utf-8');
    }
    //要替换的个数
    if ($more_number) {
        $e_more = '';
        for ($i = 0; $i < $str_length - $front - $after; $i++) {
            $e_more = $e_more . $more;
        }

        return $arr[0] . $e_more . $arr1[1];
    } else {
        return $arr[0] . $more . $arr1[1];
    }
}

/*
 * 生成店铺二维码
 */
function twoCode($id, $business_id)
{
    $imgurl = SITE_URL_M . '/order/pay?store_id=' . $id . '&business_id=' . $business_id; //图片链接数据
    $suiji = mt_rand(1, 999);
    $h_name = md5(time() . $suiji);
    $img = $id . $h_name . '.png'; //图片名称
    $img_path = 'Public/upload/twoCode/'; //图片路径
    $dir = $img_path . $img;
    if (!(is_dir($img_path)))
        mkdir($img_path, 0777, TRUE);
    include_once 'Application/Common/Common/twoCode/phpqrcode/phpqrcode.php';
    $img_erwei = \QRcode::png($imgurl, $dir);
    $upyun = new \Common\Common\util\UpYun(UPYUN_BUCKET, UPYUN_NAME, UPYUN_PWD);
    try {
        $fh = fopen($dir, 'rb');
        $rsp = $upyun->writeFile('/twoCode/' . $img, $fh, TRUE);   // 上传图片，自动创建目录
    } catch (\Exception $e) {
        echo $e->getCode();
        echo $e->getMessage();
    }
    fclose($fh);
    unlink($dir);

    return $img_url = UPYUN_DOMAIN . '/twoCode/' . $img;
}

/**
 * 验证传递的数字是否为正整数
 * @author 406
 * @param type $data
 */
function verify_number($data, $isE = TRUE)
{
    if ((!is_numeric($data) || $data < 0) || (fmod($data, 2) != 0 && fmod($data, 2) != 1)) {
        if ($isE) {
            E('参数格式不正确', CP_ERROR);
        } else {
            return FALSE;
        }
    }

    return TRUE;
}


/**
 * @desc 判断时间间隔（昨天，小时前，分钟前，刚刚）
 * @author 406
 * @param string $time 时间戳 时间戳必须小于等于当前时间戳
 *         boolea $time 时间戳 时间戳必须小于等于当前时间戳
 * @return string 返回具体结果
 */
function date_time($time, $is_week = FALSE)
{
    //获取今天凌晨的时间戳
    $day = strtotime(date('Y-m-d', time()));
    //获取昨天凌晨的时间戳
    $pday = strtotime(date('Y-m-d', strtotime('-1 day')));
    //获取现在的时间戳
    $nowtime = time();

    $tc = $nowtime - $time;
    if ($tc < 0) {
        return '';
    }
    if ($time < $pday) {
        $week_num = date('w', $time);
        switch ($week_num) {
            case 0:
                $week_string = '日';
                break;
            case 1:
                $week_string = '一';
                break;
            case 2:
                $week_string = '二';
                break;
            case 3:
                $week_string = '三';
                break;
            case 4:
                $week_string = '四';
                break;
            case 5:
                $week_string = '五';
                break;
            case 6:
                $week_string = '六';
                break;
            default :
                $week_string = '';
                break;
        }
        if ($is_week) {
            $str = '周' . $week_string . date('m-d', $time);
        } else {
            $str = date('Y-m-d H:i:s', $time);
        }

    } elseif ($time < $day && $time > $pday) {
        $str = "昨天" . date('H:i', $time);
    } elseif ($tc > 60 * 60) {
        $str = floor($tc / (60 * 60)) . "小时前";
    } elseif ($tc > 60) {
        $str = floor($tc / 60) . "分钟前";
    } else {
        $str = "刚刚";
    }

    return $str;
}

/**
 * @desc 不四舍五入截取浮点型字符串
 * @author 5058
 * @param float $f 金额含小数点
 * @param int $len 默认为4个小数点
 * @return string 返回具体结果
 */
function getFloatValue($f = '0.0000', $len = 4)
{
    //验证是否为int、float等类型
    if (!preg_match('/^(-?\d+)(\.\d+)?$/', $f)) {
        $str = '';
        for ($i = 0; $i < $len; $i++) {
            $str .= '0';
        }
        return '0.' . $str;
    }

    $loss = '';
    if ($f > -1 && $f < 0) {
        $loss = '-';
    }
    //小数点(.)有包含计算进去,所以程序长度需加1
    $len += 1;
    $tmpInt = (int)$f;
    $str = strstr($f, '.');
    if (!$str) {
        if ((int)$tmpInt != $f) {
            return $f;
        }
    }
    if (strlen($str) < $len) {
        $num = $len - strlen($str);
        //$str .= str_repeat("0",$num);
        for ($i = 0; $i < $num; $i++) {
            $str .= '0';
        }
    }

    //再次判断是否有包含小数点,预防$f为int的情况
    $str_temp = strstr($str, '.');
    if (!$str_temp) {
        $str = '.' . $str;
    }
    $str = substr($str, 0, $len);
    return $loss . $tmpInt . $str;
}

/**截取字符串长度
 * @param $str
 * @param $len 截取长度 默认6个
 * @return string
 */
function mbSubStr($str, $len = 6, $splice = '...')
{
    if (strlen($str) <= $len * 3) {
        return $str;
    }
    $st = mb_substr($str, 0, $len, 'utf-8') . $splice;
    return $st;
}

/**两个时间差日时分秒
 * @param $begin_time 开始时间戳
 * @param $end_time 结束时间戳
 * @author 5056
 */
function datetimediff($begin_time, $end_time)
{
    if ($begin_time < $end_time) {
        $starttime = $begin_time;
        $endtime = $end_time;
    } else {
        $starttime = $end_time;
        $endtime = $begin_time;
    }
    //计算天数
    $timediff = $endtime - $starttime;
    $days = intval($timediff / 86400);
    //计算小时数
    $remain = $timediff % 86400;
    $hours = intval($remain / 3600);
    //计算分钟数
    $remain = $remain % 3600;
    $mins = intval($remain / 60);
    //计算秒数
    $secs = $remain % 60;
    $res = array(
        "day" => $days,
        "hour" => $hours,
        "min" => $mins,
        "sec" => $secs
    );
    return $res;
}


/**創建一個臨時表
 * @param string $table_name 表名
 * @param array $data 需要插入的數據，表字段名，以二維數組中的第一個以為數組為準
 * @return bool
 */
function create_temporary($table_name = '', $data = array())
{
    if (empty($table_name) || empty($data)) {
        return false;
    }
    $field = '';
    $set_val_str = '';

    foreach ($data[0] as $key => $val) {
        $field .= $key . " varchar(100),";
    }
    foreach ($data as $key => $val) {
        $set_val_str .= "(";

        foreach ($val as $ke => $va) {
            $data[$key][$ke] = (string)$va;

            $set_val_str .= "'" . $va . "',";
        }
        $set_val_str = trim($set_val_str, ',');
        $set_val_str .= "),";
    }
    $field = trim($field, ',');
    $set_val_str = trim($set_val_str, ',');
    $sql = "create temporary table  " . $table_name . "(" . $field . ");";
    $sql .= "insert into $table_name  values " . $set_val_str;
    $mod = M();
    $mod->execute($sql);
}

/**查詢臨時表
 * @param $table_name 表名
 * @param int $page 分頁書
 * @param int $size 加載條數
 * @param string $field 查詢字段
 * @param string $where
 * @param string $order
 * @param string $group
 * @return mixed
 */
function get_temporary($table_name, $page = 0, $size = 20, $field = '*', $where = '', $order = '', $group = '')
{
    $mod = M();
    $sql = "select " . $field . " from " . $table_name;
    if (!empty($where)) {
        $sql .= " where " . $where;
    }
    if (!empty($group)) {
        $sql .= " group by " . $group;
    }
    if (!empty($order)) {
        $sql .= " order by " . $order;
    }
    if (!empty($page)) {
        $offset = ($page - 1) * $size;
        $sql .= " limit " . $size . " offset " . $offset;
    }
    return $mod->query($sql);
}


/**
 * 二维数据排序
 *
 * @param array 需要排序的数组
 * @param string $keys 需要排序的列 的 key
 * @param string $type asc升级 desc降序
 * @return array 返回根据 $keys 列的值按 $type 排序后的二维数组
 */
function array_sort($arr, $keys, $type = 'asc')
{
    $keysvalue = array();
    foreach ($arr as $k => $v) {
        $keysvalue[$k] = $v[$keys];
    }
    if ($type == 'asc') {
        array_multisort($keysvalue, SORT_ASC, $arr);
    } else {
        array_multisort($keysvalue, SORT_DESC, $arr);
    }
    return $arr;
}


/**
 * 查询所有城市
 *
 * @return array
 */
function getAllCity()
{
    $where['status'] = 2;
    $where['pid'] = 0;
    $res = M('city')->where($where)->select();
    return $res ? $res : array();
}


function getCityArr()
{
    $data = array();
    $where['status'] = 2;
    $res = M('city')->where($where)->select();
    foreach ($res as $key => $value) {
        $data[$value['id']] = $value['name'];
    }
    return $data;
}

/**
 * 查询战区下的店铺
 *
 * @param warzone_id 战区ID
 * @return array
 */
function getStoresByWarzoneId($warzone_id)
{
    $where['status'] = 1;
    $where['id'] = $warzone_id;
    $res = M('bi_war_zone')->where($where)->find();
    return $res['store_ids'] ? explode(',', $res['store_ids']) : array();
}

/**
 * 获取菜单全局
 *
 * @return string
 */
function getNode()
{
    $str = $ca = '';
    $access = getUserAccess();
    $datas = M("bi_node")->where("level=1 and status=1")->order('sort')->select();

    foreach ($datas as $k => $v) {
        $map['level'] = 2;
        $map['pid'] = $v['id'];
        $map['status'] = 1;
        $datas[$k]['data'] = M("bi_node")->where($map)->order('sort')->select();
    }
    foreach ($datas as $key => $value) {
        if (!in_array($value['id'], $access) && C('ADMIN_AUTH_KEY') != session('username')) {
            continue;
        }

        $mark = array_map(function ($arr) {
            return $arr['name'];
        }, $value['data']);
        if ($value['name'] == MODULE_NAME && in_array(CONTROLLER_NAME, $mark)) {
            $li = 'class="active"';
            $ui = 'style="display: block;"';
        }

        $str .= "<li {$li}><a><i class='fa fa-{$value['style']}'></i>{$value['title']}<span class='fa fa-chevron-down'></span></a><ul class='nav child_menu' {$ui}>";
        foreach ($value['data'] as $key2 => $value2) {
            if (!in_array($value2['id'], $access) && C('ADMIN_AUTH_KEY') != session('username')) {
                continue;
            }
            if ($value['name'] == MODULE_NAME && $value2['name'] == CONTROLLER_NAME && $value2['remark'] == strtolower(ACTION_NAME)) {
                $li2 = 'class="current-page"';
            }
            if ($value['name'] == 'Home') {
                $home = 'Home';
                $url = U("{$home}/{$value2['name']}/{$value2['remark']}");
            } else {
                $url = U("{$value['name']}/{$value2['name']}/{$value2['remark']}");
            }
            $str .= "<li {$li2} onclick='initload()'><a href='{$url}'>{$value2['title']}</a></li>";
            unset($li2);
        }
        $str .= '</ul></li>';
        unset($li, $ui, $mark);
    }
    return $str;
}

/**
 * 获取角色拥有的权限
 *
 * @return array
 */
function getUserAccess()
{
    $uid = session(C('USER_AUTH_KEY')) ? session(C('USER_AUTH_KEY')) : 0;
    $access = M("bi_access a")->field("a.node_id")->join('cp_bi_role_user b on a.role_id=b.role_id')->where("b.user_id={$uid}")->select();
    return $access ? array_map(function ($arr) {
        return $arr['node_id'];
    }, $access) : array();
}

/**
 * 获取某年第几周的开始日期和结束日期
 * @param int $year
 * @param int $weeknum 第几周
 * @author 6075
 * @return array
 */
function getWeekDateSD($year, $weeknum)
{
    $firstdayofyear = mktime(0, 0, 0, 1, 1, $year);
    $firstweekday = date('N', $firstdayofyear);
    $firstweenum = date('W', $firstdayofyear);
    if ($firstweenum == 1) {
        $day = (1 - ($firstweekday - 1)) + 7 * ($weeknum - 1);
        $startdate = date('Y-m-d', mktime(0, 0, 0, 1, $day, $year));
        $enddate = date('Y-m-d', mktime(0, 0, 0, 1, $day + 6, $year));
    } else {
        $day = (9 - $firstweekday) + 7 * ($weeknum - 1);
        $startdate = date('Y-m-d', mktime(0, 0, 0, 1, $day, $year));
        $enddate = date('Y-m-d', mktime(0, 0, 0, 1, $day + 6, $year));
    }
    return array($startdate, $enddate);
}

function encrypt($data, $key)
{
    $prep_code = serialize($data);
    $block = mcrypt_get_block_size('des', 'ecb');
    if (($pad = $block - (strlen($prep_code) % $block)) < $block) {
        $prep_code .= str_repeat(chr($pad), $pad);
    }
    $encrypt = mcrypt_encrypt(MCRYPT_DES, $key, $prep_code, MCRYPT_MODE_ECB);
    return base64_encode($encrypt);
}

function decrypt($str, $key)
{
    $str = base64_decode($str);
    $str = mcrypt_decrypt(MCRYPT_DES, $key, $str, MCRYPT_MODE_ECB);
    $block = mcrypt_get_block_size('des', 'ecb');
    $pad = ord($str[($len = strlen($str)) - 1]);
    if ($pad && $pad < $block && preg_match('/' . chr($pad) . '{' . $pad . '}$/', $str)) {
        $str = substr($str, 0, strlen($str) - $pad);
    }
    return unserialize($str);
}

//生成借款单编号
function loanBill_no()
{
    $data = 'JK' . date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    return $data;
}

//生成报销单编号
function reimbursement_no()
{
    $data = 'BX' . date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    return $data;
}


function admin_md5($str)
{
    $key = 'Ld)Oc~0.Eq5[e,r<C^(dpHp|JTz}mu>M"=*@6N]ov#auth_Key';
    return '' === $str ? '' : md5(sha1($str) . $key);
}

function getRoleArr($staff_number, $company_id)
{
    $where['staff_number'] = $staff_number;
    $where['company_id'] = $company_id;
    $res = M('cost_role_user')
        ->field('company_mger,member_mger,budget_mger,ceo,competent,treasurer,cashier,contract')
        ->where($where)->select();
    foreach ($res as $key => $value) {
        foreach ($value as $key2 => $value2) {
            $data[$key2] += $value2;
        }
    }
    return $data ? $data : array();
}


/**
 * 验证验证码
 *
 * @param string $nchash 哈希数
 * @param string $value 待验证值
 * @return boolean
 */
function checkSeccode($nchash, $value)
{
    list($checkvalue, $checktime, $checkidhash) = explode("\t", decrypt(cookie('seccode' . $nchash), MD5_KEY));
    $return = $checkvalue == strtoupper($value) && $checkidhash == $nchash;
    if (!$return) cookie('seccode' . $nchash, '', -3600);
    return $return;
}


/**
 * 检测FORM是否提交
 * @param  $check_token 是否验证token
 * @param  $check_captcha 是否验证验证码
 * @param  $return_type 'alert','num'
 * @return boolean
 */
function chksubmit($check_token = false, $check_captcha = false, $return_type = 'alert', $check_verify_code = false)
{
    //$submit = isset($_POST['form_submit']) ? $_POST['form_submit'] : $_GET['form_submit'];

    //验证是否来自指定页面
    //if ($submit != 'ok') return false;
    //验证token
    if ($check_token && !Security::checkToken()) {
        if ($return_type == 'alert') {
            showDialog('Token error!');
        } else {
            return -11;
        }
    }
    //图片验证码
    if ($check_captcha) {
        if (!checkSeccode($_POST['nchash'], $_POST['captcha'])) {
            if ($return_type == 'alert') {
                showDialog('验证码错误!');
            } else {
                return -12;
            }
        }
        cookie('seccode' . $_POST['nchash'], '', -3600);
    }

    //手机验证码
    if ($check_verify_code) {
        $verify_code = cookie('verify_code');
        if (empty($verify_code)) {
            return -14;
            showDialog('手机验证码错误,请重新发送！');
        }
        if (strcmp($verify_code, $_POST['verify_code']) != 0) {
            if ($return_type == 'alert') {
                showDialog('手机验证码错误!');
            } else {
                return -13;
            }
        }
        cookie('verify_code', '', -3600);
    }
    return true;
}


?>